<template>
  <a-spin :spinning="loading">
    <div style="margin-top: 10px;padding-bottom:15px;">
      <a-card>
        <a-row>
          <a-col :span="24">
            <span style="font-size: 22px;font-weight: 700">{{ form.title }} </span>
          </a-col>
        </a-row>
        <a-row style="margin-top: 20px">
          <a-col :span="12">
            <span style="color: #00bb00">开始时间：</span><span
            class="groupCardFont">{{ form.startTime
            }}</span>
          </a-col>
          <a-col :span="12">
            <span style="color: #00bb00">截止时间：</span><span class="groupCardFont">{{ form.endTime
            }}</span>
          </a-col>
        </a-row>
      </a-card>
      <a-card title="考试概述" style="margin-top: 10px">
        <div class="groupCard">
          <a-row>
            <a-col :span="8">
              考试时长：<span class="groupCardFont">{{ form.totalTime }}</span> 分钟
            </a-col>
            <a-col :span="8">
              考试总分：<span class="groupCardFont">{{ form.paper.totalScore || 0 }}</span> 分
            </a-col>
            <a-col :span="8">
              及格分数：<span class="groupCardFont">{{ form.qualifyScore }}</span> 分
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="8">
              试题总数：<span class="groupCardFont">{{ form.paper.questionCount || 0 }}</span> 题
            </a-col>
            <a-col :span="8">
              限考次数：<span class="groupCardFont">{{ form.limitCount || "--" }}</span> 次
            </a-col>
            <a-col :span="8">
              开放权限：{{ form.openType_dictText }}
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="8">
              试卷名称：{{ form.paper.title }}
            </a-col>
            <a-col :span="8">
              组卷方式：{{ form.paper.joinType_dictText }}
            </a-col>
            <a-col :span="8">
              已考次数：<span class="groupCardFont">{{ form.tryCount || 0 }}</span> 次
            </a-col>
          </a-row>
        </div>
      </a-card>
      <a-card title="考生须知">
        <Typography>
          <TypographyParagraph>
            （1）点击开始考试后将自动进入考试，请遵守考场纪律诚信考试。
          </TypographyParagraph>
          <TypographyParagraph>
            （2）考试试题，共{{
              form.paper.questionCount
            }}题，每套试卷{{
              form.paper.joinType == 1 || form.paper.joinType == 3 ? "固定选取" : form.paper.joinType == 2 ? "随机抽取" : ""
            }}{{ form.paper.questionCount }}题，
            <span v-if="form.questionTypeCountList &&form.questionTypeCountList.length > 0">
              其中<span v-for="(item, index) in form.questionTypeCountList" :key="index">
                {{ item.questionTypeName }}{{ item.questionCount }}题，
                </span>
            </span>
            总分{{
              form.paper.totalScore
            }}分，{{ form.qualifyScore }}分及格。
          </TypographyParagraph>
          <TypographyParagraph>
            （3）考试任务，需在{{ form.totalTime }}分钟内完成考试任务并提交。<span
            v-if="form.limitCount > 0">每位考生有{{ form.limitCount }}次考试机会。</span><span
            v-if="form.leaveOn">考试开始后，切屏超过{{ form.totalLeaveTimes
            }}次则视为自动交卷。</span>
          </TypographyParagraph>
          <TypographyParagraph  >
            （4）进入考试后，请勿切屏，如果切屏会影响最终考试成绩。
          </TypographyParagraph>
          <TypographyParagraph v-if="form.snapOn">
            （5）进入考试后，每隔{{ form.snapIntervalTime }}分钟，摄像头会抓拍考生答题照片。
          </TypographyParagraph>
        </Typography>
      </a-card>
      <div style="width: 100%; margin-top:20px;text-align: center">
        <a-space size="large">
          <a-button @click="startExam" danger type="primary" v-if="form.state == 0 && !isToLimit">
            开始考试
          </a-button>
          <a-button @click="viewScore" type="primary" color="warning" v-if="!!isExamRecord">
            查看成绩
          </a-button>
          <a-button @click="download" type="dashed" color="warning" v-if="!!certificate">
            下载考试证书
          </a-button>
        </a-space>
      </div>
    </div>
  </a-spin>
  <a-modal title="考试成绩" :open="showScore" :footer="null" @cancel="showScore=false">
    <UserExamScoreModal :record="scoreRecord" v-if="scoreRecord" />
  </a-modal>

  <a-modal title="人脸认证" :open="showFaceDetect" :footer="null" @cancel="showFaceDetect=false"
           width="900px" destroy-on-close>
    <WebRTCFace :imageBase64="`data:image/jpeg;base64,${imageBase64}`"
                v-if="!!imageBase64"
                @goToExam="goToExam" />
  </a-modal>
</template>

<script lang="ts" setup>
import { createVNode, onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import {
  apiCheckToLimit,
  apiCreateExam,
  apiExamRecordExist,
  apiGetUserExamScore,
  apiListExamIn,
  apiQueryExamById
} from "@/api/exam";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { Modal, Typography, TypographyParagraph } from "ant-design-vue";
import { useMessage } from "@/hooks/web/useMessage";
import UserExamScoreModal from "@/components/exam/UserExamScoreModal.vue";
import WebRTCFace from "@/components/face/WebRTCFace.vue";
import { useWebStore } from "@/store";
import { apiReadImageBase64 } from "@/api/user";
import { apiGetUserCertificate } from "@/api/certificate";
import { downloadFile } from "@/api/common/api";

const webStore = useWebStore();
const userInfo = ref<any>({});

const router = useRouter();

const { createMessage } = useMessage();
const loading = ref<boolean>(false);
const scoreRecord = ref<any>();
const showScore = ref<boolean>(false);
const showFaceDetect = ref<boolean>(false);
const imageBase64 = ref<any>();

const props = defineProps({
  examId: { type: String }
});

const labelCol = reactive({
  xs: { span: 24 },
  sm: { span: 5 }
});
const wrapperCol = reactive({
  xs: { span: 24 },
  sm: { span: 16 }
});

const form = ref<any>({
  paper: {}
});

//是否有考试记录
const isExamRecord: any = ref<boolean>(false);
const isToLimit: any = ref<boolean>(false);
const certificate = ref<any>();

async function initFormData() {
  loading.value = true;
  try {
    const checkData: any = await apiCheckToLimit(props.examId);
    isToLimit.value = checkData.result;

    const data: any = await apiQueryExamById(props.examId);
    if (data.result && !data.result?.paper) {
      createMessage.error("未找到对应试卷");
      return false;
    }
    form.value = { ...data.result };
    const recordData: any = await apiExamRecordExist(props.examId);
    isExamRecord.value = recordData.result;

    if (data.result?.certificateId) {
      const result: any = await apiGetUserCertificate(data.result.certificateId, data.result.id, "");
      certificate.value = result?.result;
    }

    //读取人脸核身base64
    if (userInfo.value?.imageBase64) {
      const res: any = await apiReadImageBase64();
      imageBase64.value = res?.result;
    }
  } finally {
    loading.value = false;
  }
}

onMounted(() => {
  userInfo.value = webStore.getUserInfo;
  initFormData();
});


//去考试
async function goToExam() {
  showFaceDetect.value = false;
  await create();
}

/**
 * 开始考试
 */
async function startExam() {
  //是否有正在进行中的考试
  const data: any = await apiListExamIn();
  if (data.result && data.result.id) {//有
    confirm(data.result);
  } else {
    if (form.value?.faceDetectEnable) {//考试是否启用人脸核身
      if (!userInfo.value?.imageBase64) {
        createMessage.error("本场考试需要进行人脸核身，请上传人脸核身照片");
        return;
      }
      showFaceDetect.value = true;
    } else {
      await create();
    }
  }
}

async function viewScore() {
  const record: any = await apiGetUserExamScore(props.examId);
  scoreRecord.value = record.result;
  showScore.value = true;
}

//确认对话框
const confirm = (data) => {
  Modal.confirm({
    title: "提示",
    icon: createVNode(ExclamationCircleOutlined),
    content: "您有其它正在进行的考试，是否继续进入该考试?",
    onOk() {
      //使用setTimeout修复确认框闪现问题
      setTimeout(() => {
        onlineExam(data.id);
      }, 100);
    },
    onCancel() {
    }
  });
};


//创建用户考试
async function create() {
  if (!form.value.id) {
    createMessage.error("未找到对应试卷");
    return;
  }
  loading.value = true;
  try {
    const data: any = await apiCreateExam(form.value.id);
    onlineExam(data.result.id);
  } finally {
    loading.value = false;
  }
}

//打开在线考试页面
function onlineExam(id) {
  let url = router.resolve({
    path: `/exam/onlineExam/` + id
  });
  window.open(url.href, "_blank");
}

function download() {
  const fileName = certificate.value?.certificatePath.substring(certificate.value.certificatePath.lastIndexOf("/") + 1);
  downloadFile(`/certificate/downloadCertificate?objectName=${certificate.value.certificatePath}&fileName=${fileName}`, fileName);
}
</script>

<style scoped>
.groupCard {
  line-height: 28px;
  font-size: 14px;
  margin-bottom: 15px;
}

.groupCardFont {
  color: #1890FF;
  font-style: italic
}
</style>
